// for actions, see: http://redux.js.org/docs/basics/Actions.html
// for some conventions, see: https://github.com/acdlite/flux-standard-action

import AuthConstants from '../constants/authentication';
import {Promise} from 'es6-promise';
import Storage from '../utils/storage';
import 'whatwg-fetch';
import { pushState } from 'redux-router';
import { browserHistory } from 'react-router'


const PROFILE_STORAGE_KEY = 'token';

export const registerRequest = () => ({
  type: AuthConstants.REGISTER_REQUEST
})

export const registerSuccess = () => ({
    type: AuthConstants.REGISTER_SUCCESS
});

export const registerError = (status) => ({
    type: AuthConstants.REGISTER_ERROR,
    payload: new Error(status),
    error: status
});

export const loginRequest = () => ({
    type: AuthConstants.LOG_IN_REQUEST
});

export const loginSuccess = (user) => {
    return {
      type: AuthConstants.LOG_IN_SUCCESS,
      payload: {
          user
      }
    }
};

export const loginError = (status) => ({
    type: AuthConstants.LOG_IN_ERROR,
    payload: new Error(status),
    error: status
});

// export const logOutSuccess = () => {
//     browserHistory.push('/#/login')
//     return {
//       type: AuthConstants.LOG_OUT
//     }
// }

// export const logout = () => {
//     Storage.remove(PROFILE_STORAGE_KEY);
//     return (dispatch) => {
//       dispatch(logOutSuccess());
//     }
// }

export const login = (formData) => {
    const {email, password} = formData;
    return (dispatch) => {
        dispatch(loginRequest());

        fetch('http://localhost:8088/user/sign_in', {
          method: 'post',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: `email=${email}&password=${password}`
        })
        .then((response) => {
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          return response.text();
        })
        .then((info) => {
            if(JSON.parse(info).info.code != 501) {
              dispatch(loginSuccess());
              Storage.set('token', JSON.stringify(formData));
            } else {
              dispatch(loginError(JSON.parse(info).info.codeMessage));
            }
            Storage.set('token', JSON.stringify(formData));
          // this.history.pushState(null, '/search');
        })
        .catch((err) => {
          dispatch(loginError(err));
        });
    };
};

export const register = (formData) => {
    const {email, password,username,sid} = formData;

    return (dispatch) => {
        dispatch(registerRequest());
        fetch('http://localhost:8088/user/sign_up', {
          method: 'post',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: `email=${email}&password=${password}&username=${username}&sid=${sid}`
        })
        .then((response) => {
          if (response.code == 501) {
            throw new Error(response.statusText);
          }
          return response.text();
        })
        .then((info) => {
            console.log(JSON.parse(info).info);
            if(JSON.parse(info).info.code != 501) {
              dispatch(registerSuccess());
              Storage.set('token', JSON.stringify(formData))
            } else {
              dispatch(registerError(JSON.parse(info).info.codeMessage));
            }
        })
        .catch((err) => {
          dispatch(registerError(err));
        });
    };
};
